package org.wells.dlock.zk.pool;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * zk连接工厂
 * 
 * @author HuangSiwei
 * @date 2020/01/21
 */
public class ZkConnectionFactory extends BasePooledObjectFactory<CuratorFramework> {
	private String zkAddress;

	private int baseSleepTimeMs;
	private int maxRetries;

	public ZkConnectionFactory(String zkAddress, int baseSleepTimeMs, int maxRetries) {
		super();
		this.zkAddress = zkAddress;
		this.baseSleepTimeMs = baseSleepTimeMs;
		this.maxRetries = maxRetries;
	}

	@Override
	public CuratorFramework create() {
		// 创建zk client
		CuratorFramework client = CuratorFrameworkFactory.newClient(this.zkAddress,
				new ExponentialBackoffRetry(this.baseSleepTimeMs, this.maxRetries));
		return client;
	}

	/**
	 * Use the default PooledObject implementation.
	 */
	@Override
	public PooledObject<CuratorFramework> wrap(CuratorFramework buffer) {
		return new DefaultPooledObject<>(buffer);
	}

	@Override
	public void activateObject(PooledObject<CuratorFramework> p) throws Exception {
		// TODO Auto-generated method stub
		 super.activateObject(p);
		 
		 p.getObject().start();
	}

	/**
	 * When an object is returned to the pool, clear the buffer.
	 */
	@Override
	public void passivateObject(PooledObject<CuratorFramework> pooledObject) {
		// pooledObject.getObject().setLength(0);
	}

	/*
	 * public static void main(String[] args) throws IOException { ReaderUtil
	 * readerUtil = new ReaderUtil(new GenericObjectPool<StringBuffer>(new
	 * ZkConnectionFactory()));
	 * 
	 * Reader in = new FileReader(new File("d:/a.txt")); String string =
	 * readerUtil.readToString(in); System.out.println(string); }
	 */
}